# coding=utf-8
import urllib
import wave
import Image

def main():
	# 下载wav
	template = "http://butter:fly@www.pythonchallenge.com/pc/hex/lake%d.wav"
	fname = r'lake%02d.wav'
	proxies = {'http':'http://127.0.0.1:8000'}
	opener = urllib.URLopener(proxies)
	i = 1
	while True:
		try:
			opener.retrieve(template % i, fname % i)
		except:
			break
		else:
			i += 1
	
	print i-1 # 25, 刚好是图片上的25个子块,平成一个图片？
	imgs = []
	for j in range(1, i):
		tmpw = wave.open(ur'lake%02d.wav' % j)
		print tmpw.getnframes() # 10800, 3字节为1像素，3600个像素, 应该是60*60的图片.
		tmpi = Image.new('RGB', (60,)*2)
		tmpi.fromstring(tmpw.readframes(tmpw.getnframes()))
		imgs.append(tmpi)
	img = Image.new('RGB', (300,)*2)   # 60*5
	for i in range(len(imgs)):
		img.paste(imgs[i], (60*(i%5), 60*(i//5))) #先行后列
	img.save('25.png', 'png')
	img.show()
	# 'decent'
	# 下一关：http://www.pythonchallenge.com/pc/hex/decent.html

if __name__ == '__main__':
	main()
